#!/bin/bash

runCommand()
{
    if [ "$1" == "mpirun" ]; then sol=$4; else sol=$1; fi
    if [ -f log.$sol ]; then rm log.$sol; fi
    "$@" 1> >(tee -a log.$sol) 2> >(tee -a log.$sol >&2)
    err=$?
    if [ ! $err -eq 0 ]; then exit $err; fi
}

%{%(system/FoamRuntime%)
%:BlueCFD
%:default
# Unset and source bashrc
if [ -f "%(system/TranslatedFoamPath%)/etc/config/unset.sh" ]; then  # for OF < 4
   source "%(system/TranslatedFoamPath%)/etc/config/unset.sh" 2> /dev/null
else
   source "%(system/TranslatedFoamPath%)/etc/config.sh/unset" 2> /dev/null
fi
source "%(system/TranslatedFoamPath%)/etc/bashrc"

%}
# Create symbolic links to polyMesh.org
if [ ! -d constant/polyMesh ]; then
    mkdir constant/polyMesh
    ln -s ../polyMesh.org/boundary constant/polyMesh
    ln -s ../polyMesh.org/faces constant/polyMesh
    ln -s ../polyMesh.org/neighbour constant/polyMesh
    ln -s ../polyMesh.org/owner constant/polyMesh
    ln -s ../polyMesh.org/points constant/polyMesh
    if [ -f constant/polyMesh.org/faceZones ]; then
        ln -s ../polyMesh.org/faceZones constant/polyMesh
    fi
fi

# Update patch name and type
runCommand createPatch -overwrite

%{%(zonesPresent%)
%:True
# Scaling .stl files exported from FreeCAD from mm to m
%{%(zones%)
%{%(zones/%(0%)/PartNameList%)
runCommand surfaceTransformPoints -scale "(0.001 0.001 0.001)" "constant/triSurface/%(0%).stl" "constant/triSurface/%(0%)Scaled.stl"

%}
%}
# Set cell zones contained inside the .stl surfaces
runCommand topoSet -dict system/topoSetZonesDict

%}
%{%(initialisationZonesPresent%)
%:True
# Set internal fields according to setFieldsDict
runCommand setFields

%}
%{%(bafflesPresent%)
%:True
%{%(createPatchesFromSnappyBaffles%)
%:False
# Combine mesh faceZones
runCommand topoSet -dict system/topoSetBafflesDict

# Creating baffles
runCommand createBaffles -overwrite

%}
%}
%{%(runChangeDictionary%)
%:True
# Update patch name and type
runCommand changeDictionary

%}
%{%(initialValues/PotentialFoam%)
%:True
# Initialise flow
runCommand potentialFoam -initialiseUBCs
%}
%{%(solver/parallel%)
%:True
# Run application in parallel
runCommand decomposePar -force
runCommand mpirun -n %(solver/parallelCores%) %(solver/solverName%) -parallel
%:False
# Run application
runCommand %(solver/solverName%)
%}

